<template>
  <div id="map" class="box-border relative w-full h-full imgBg">
    <div class="absolute top-[60px] left-1/2 -translate-x-1/2 z-10 flex">
      <popover placement="bottom">
        <div class="w-[195px]">
          <div
            v-for="(item, index) in pipelineList"
            :key="item.id"
            class="px-4 py-2 text-center cursor-pointer hover:bg-gray-100"
            @click="handlePipelineSelect(item)"
          >
            {{ item.value }}
          </div>
        </div>
      </popover>
      <button
        class="w-[195px] h-[47px] backdrop-blur-sm flex items-center justify-center border-none rounded-md text-black text-base cursor-pointer duration-300"
        :class="isActiveParams ? 'bg-white' : 'bg-white/40 hover:bg-white/70'"
        @click="toggleParams"
      >
        管道及站场基础参数
      </button>
      <button
        class="w-[195px] h-[47px] backdrop-blur-sm flex items-center justify-center border-none rounded-md text-black text-base cursor-pointer duration-300 ml-20"
        :class="isActiveTable ? 'bg-white' : 'bg-white/40 hover:bg-white/70'"
        @click="toggleTable"
      >
        全线参数总表
      </button>
    </div>
    <el-dialog
      v-model="dialogParamsVisible"
      width="62%"
      @close="handleParamsDialogClose"
      class="params-dialog"
      draggable
    >
      <template #header>
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="管道参数表" name="params1">
            <div class="flex justify-center gap-4 mb-6">
              <div
                class="flex items-center justify-center custom-button5"
                :class="{ 'custom-button6': curIndex === item.id }"
                @click="changeCurIndex(item.id)"
                v-for="item in buttons"
                :key="item.id"
              >
                {{ item.name }}
              </div>
            </div>
            <div>
              <!-- 管道参数表格 -->
              <div class="mt-6 mb-4 text-lg font-bold">
                {{ currentPipelineData[0].name }}管道参数表
              </div>
              <el-table :data="currentPipelineData" border>
                <el-table-column label="管线名称" prop="pipeline_name" align="center" />
                <el-table-column label="管材" prop="material" align="center" />
                <el-table-column label="管径（mm）" prop="diameter" align="center" />
                <el-table-column label="壁厚（mm）" prop="wall_thickness" align="center" />
                <el-table-column
                  label="设计压力（MPa）"
                  prop="design_pressure"
                  align="center"
                  width="200"
                />
                <el-table-column
                  label="保温层厚度（mm）"
                  prop="insulation_thickness"
                  align="center"
                  width="200"
                />
                <el-table-column
                  label="防腐层材料"
                  prop="anti_corrosion_material"
                  align="center"
                  width="200"
                />
                <el-table-column label="备注" prop="notes" align="center" />
              </el-table>

              <!-- 泵池信息表格 -->
              <div v-if="currentPumpData.length > 1">
                <div class="mt-6 mb-4 text-lg font-bold">沿线阀池信息</div>
                <el-table :data="[{ type: '里程 km', value: '' }]" border>
                  <el-table-column label="名称" prop="type" width="120" align="center" />
                  <el-table-column
                    v-for="(item, index) in currentPumpData"
                    :key="index"
                    :label="item.valve_pool_name"
                    align="center"
                  >
                    <template #default="scope">
                      {{ scope.row.type === '名称' ? item.valve_pool_name : item.mileage }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 管道纵断面图 -->
              <div class="mt-6 mb-4 text-lg font-bold">管道纵断面图</div>
              <div ref="pipelineChartRef" class="h-[300px]"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="输油泵参数表" name="params2">
            <el-table :data="pumpParamsData" border :span-method="pumpParamsSpanMethod">
              <el-table-column prop="station_name" label="站场名称" align="center" />
              <el-table-column prop="pump_number" label="泵编号" align="center" />
              <el-table-column prop="pump_model" label="泵型号" align="center" />
              <el-table-column prop="matching_power" label="配用功率(kW)" align="center" />
              <el-table-column prop="headlift" label="扬程(m)" align="center" />
              <el-table-column prop="displacement" label="排量(m³/h)" align="center" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="站场运行参数保护设定值" name="params3">
            <el-table :data="stationParamsData" border :span-method="stationParamsSpanMethod">
              <el-table-column prop="station_name" label="站场" align="center" />
              <el-table-column prop="location" label="位置" align="center" />
              <el-table-column label="温度/℃" align="center">
                <el-table-column prop="temp_low_low" label="低低" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.temp_low_low"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="temp_low" label="低" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.temp_low"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="temp_high" label="高" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.temp_high"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="temp_high_high" label="高高" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.temp_high_high"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="压力/MPa" align="center">
                <el-table-column prop="pressure_low_low" label="低 低" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.pressure_low_low"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="pressure_low" label="低" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.pressure_low"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="pressure_high" label="高" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.pressure_high"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="pressure_high_high" label="高高" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.pressure_high_high"
                      @change="handleCellChange(scope.row)"
                      size="small"
                      placeholder="-"
                    />
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column prop="notes" label="备注" align="center">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.notes"
                    @change="handleCellChange(scope.row)"
                    size="small"
                    placeholder="-"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="油品物性表" name="params4">
            <div class="flex justify-end mb-2">
              <div class="custom-button2" @click="handleAddOil">+ 新增</div>
            </div>
            <el-table
              :data="oilData"
              border
              :header-cell-style="{
                // color: '#fff',
                fontWeight: '600'
              }"
            >
              <el-table-column
                prop="chinese_name"
                label="油品名称"
                align="center"
                header-align="center"
              />
              <el-table-column
                prop="oils_name"
                label="油品编号"
                align="center"
                header-align="center"
              />
              <el-table-column
                prop="density"
                label="密度（kg/m3）"
                align="center"
                header-align="center"
              />
              <el-table-column
                prop="viscosity"
                label="粘温关系"
                align="center"
                header-align="center"
              >
                <template #default="scope">
                  <div class="flex items-center justify-center">
                    <img
                      src="../../assets/images/editImg2.png"
                      class="w-5 h-5 cursor-pointer"
                      @click="handleViscosityEdit(scope.row)"
                    />
                  </div> </template
              ></el-table-column>
              <!-- <el-table-column
                prop="specific_heat"
                label="比热容(kJ/kg∙℃)"
                align="center"
                header-align="center"
              /> -->
              <el-table-column
                prop="freezing_point"
                label="凝点（℃）"
                align="center"
                header-align="center"
              />
              <el-table-column
                prop="base_viscosity"
                label="基准粘度（mpa.s）"
                align="center"
                header-align="center"
              />
              <!-- <el-table-column
                prop="thermal_conductivity"
                label="导热系数(W/m∙K)"
                align="center"
                header-align="center"
              /> -->

              <el-table-column label="操作" align="center" header-align="center">
                <template #default="scope">
                  <div class="flex items-center justify-center">
                    <div class="flex gap-2">
                      <div class="custom-button3" @click="handleEdit(scope.row)">编辑</div>
                      <div class="custom-button4" @click="handleDelete(scope.row)">删除</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-dialog>
    <!-- 新增油品信息弹窗 -->
    <el-dialog v-model="oilFormVisible" width="440" @close="handleOilFormClose" draggable>
      <template #header>
        <div class="flex items-center gap-1 ml-2">
          <img :src="isEdit ? editImg : addImg" class="w-5 h-5" alt="icon" />
          <span>{{ isEdit ? '编辑油品' : '新增油品' }}</span>
        </div>
      </template>

      <el-form ref="oilFormRef" :model="oilForm" :rules="rules" label-width="150px">
        <el-form-item label="油品名称" prop="chinese_name">
          <el-input v-model="oilForm.chinese_name" placeholder="请输入油品名称" class="!w-3/5" />
        </el-form-item>
        <el-form-item label="油品编号" prop="oils_name">
          <el-input v-model="oilForm.oils_name" placeholder="请输入油品编号" class="!w-3/5" />
        </el-form-item>

        <el-form-item label="密度（kg/m3）" prop="density">
          <el-input v-model="oilForm.density" placeholder="请输入密度" class="!w-3/5" />
          <span class="ml-2 text-white">kg/m³</span>
        </el-form-item>

        <el-form-item label="粘温关系" prop="viscosity">
          <img
            src="../../assets/images/editImg2.png"
            class="w-5 h-5 ml-5 cursor-pointer"
            @click="handleViscosityEdit2"
          />
        </el-form-item>
        <!-- <el-form-item label="比热容" prop="specific_heat">
          <el-input v-model="oilForm.specific_heat" placeholder="请输入比热容" class="!w-3/5" />
          <span class="ml-2 text-white">kJ/kg∙℃</span>
        </el-form-item> -->
        <el-form-item label="凝点（℃）" prop="freezing_point">
          <el-input v-model="oilForm.freezing_point" placeholder="请输入凝点" class="!w-3/5" />
          <span class="ml-2 text-white">℃</span>
        </el-form-item>
        <el-form-item label="基准粘度（mpa.s）" prop="base_viscosity">
          <el-input v-model="oilForm.base_viscosity" placeholder="请输入基准粘度" class="!w-3/5" />
          <span class="ml-2 text-white">mPa·s</span>
        </el-form-item>

        <!-- <el-form-item label="导热系数" prop="thermal_conductivity">
          <el-input
            v-model="oilForm.thermal_conductivity"
            placeholder="请输入导热系数"
            class="!w-3/5"
          />
          <span class="ml-2 text-white">W/m∙K</span>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="flex justify-center w-full gap-4">
          <el-button
            color="rgba(69, 122, 178, 1)"
            class="!font-bold"
            :icon="Check"
            @click="handleOilFormSubmit"
            >确定</el-button
          >
          <el-button type="info" class="!font-bold" :icon="Close" @click="handleOilFormClose"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 添加运行参数编辑弹窗 -->
    <el-dialog v-model="paramsFormVisible" width="440" @close="handleParamsFormClose" draggable>
      <template #header>
        <div class="flex items-center gap-1 ml-2">
          <img :src="editImg" class="w-5 h-5" alt="icon" />
          <span>编辑运行参数</span>
        </div>
      </template>

      <el-form ref="paramsFormRef" :model="paramsForm" :rules="paramsRules" label-width="120px">
        <el-form-item label="站场流量上限" prop="flow_upper_limit">
          <el-input
            v-model="paramsForm.flow_upper_limit"
            placeholder="请输入流量上限"
            class="!w-3/5"
          />
        </el-form-item>
        <el-form-item label="站场流量下限" prop="flow_lower_limit">
          <el-input
            v-model="paramsForm.flow_lower_limit"
            placeholder="请输入流量下限"
            class="!w-3/5"
          />
        </el-form-item>
        <el-form-item label="站场压力上限" prop="pressure_upper_limit">
          <el-input
            v-model="paramsForm.pressure_upper_limit"
            placeholder="请输入压力上限"
            class="!w-3/5"
          />
        </el-form-item>
        <el-form-item label="站场压力下限" prop="pressure_lower_limit">
          <el-input
            v-model="paramsForm.pressure_lower_limit"
            placeholder="请输入压力下限"
            class="!w-3/5"
          />
        </el-form-item>
        <el-form-item label="出站压力上限" prop="outlet_pressure_upper_limit">
          <el-input
            v-model="paramsForm.outlet_pressure_upper_limit"
            placeholder="请输入出站压力上限"
            class="!w-3/5"
          />
        </el-form-item>
        <el-form-item label="出站压力下限" prop="outlet_pressure_lower_limit">
          <el-input
            v-model="paramsForm.outlet_pressure_lower_limit"
            placeholder="请输入出站压力下限"
            class="!w-3/5"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="flex justify-center w-full gap-4">
          <el-button type="primary" :icon="Check" @click="handleParamsFormSubmit">确定</el-button>
          <el-button type="info" :icon="Close" @click="handleParamsFormClose">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加全线参数总表弹 -->
    <el-dialog
      v-model="tableDialogVisible"
      title="全线参数总表"
      width="68%"
      :before-close="handleTableDialogClose"
      class="parameters-table-dialog"
      draggable
    >
      <el-table :data="parametersData" border>
        <el-table-column prop="station_name" label="站名" align="center" />
        <el-table-column prop="inlet_pressure" label="进站压力(MPa)" align="center" />
        <el-table-column prop="outlet_pressure" label="出站压力(MPa)" align="center" />
        <el-table-column prop="inlet_temperature" label="进站温度(℃)" align="center" />
        <el-table-column prop="outlet_temperature" label="出站温度(℃)" align="center" />
        <el-table-column prop="outFlow" label="出站流量(m³/h)" align="center" />
        <el-table-column prop="inFlow" label="进站流量(m³/h)" align="center" />
      </el-table>
    </el-dialog>

    <!-- 加新的弹窗 -->
    <el-dialog
      v-model="pipelineParamsVisible"
      :title="pipelineData.name + '管道站场基础参数'"
      width="80%"
      draggable
    >
      <div class="pipeline-params-table">
        <!-- 管段基本信息表格 -->
        <el-table
          :data="[pipelineData]"
          border
          style="margin-bottom: 20px"
          :header-cell-style="{ color: '#000000', fontWeight: '500' }"
        >
          <el-table-column label="管段长度(km)" prop="length" align="center" />
          <el-table-column label="管径(mm)" prop="diameter" align="center" />
          <el-table-column label="壁厚(mm)" prop="thickness" align="center" />
          <el-table-column label="设计输量(万吨/年)" prop="design_capacity" align="center" />
          <el-table-column label="设计压力(MPa)" prop="design_pressure" align="center" />
        </el-table>

        <!-- 站场信息表格 -->
        <el-table
          :data="getTableData(pipelineData)"
          :span-method="objectSpanMethod"
          border
          :header-cell-style="{ color: '#000000', backgroundColor: '#f5f7fa', fontWeight: '500' }"
        >
          <el-table-column label="站场名称" prop="stationName" align="center" />
          <el-table-column label="里程(km)" prop="mileage" align="center" />
          <el-table-column label="高程(m)" prop="elevation" align="center" />
          <el-table-column label="泵编号" prop="pumpNo" align="center" />
          <el-table-column label="配用功率(kW)" prop="pump_power" align="center" />
          <el-table-column label="扬程(m)" prop="pump_head" align="center" />
          <el-table-column label="排量(m³/h)" prop="pump_flow" align="center" />
        </el-table>
      </div>
    </el-dialog>
    <!-- 添加粘温关系弹窗 -->
    <el-dialog
      v-model="viscosityDialogVisible"
      title="粘温关系"
      width="500px"
      @close="handleViscosityDialogClose"
      draggable
    >
      <div class="flex justify-end mb-4">
        <div class="custom-button2" @click="addViscosityRow">+ 新增</div>
      </div>
      <el-table :data="viscosityData" border class="viscosity-table">
        <el-table-column label="温度(℃)" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.temperature" placeholder="请输入温度" />
          </template>
        </el-table-column>
        <el-table-column label="粘度(mpa.s)" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.viscosity" placeholder="请输入粘度" />
          </template>
        </el-table-column>
        <!-- 添加操作列 -->
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="deleteViscosityRow(scope.$index)"
              :disabled="viscosityData.length === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="flex justify-center w-full gap-4">
          <el-button
            color="rgba(69, 122, 178, 1)"
            class="!font-bold"
            :icon="Check"
            @click="handleViscosityConfirm"
            >确定</el-button
          >
          <el-button
            type="info"
            class="!font-bold"
            :icon="Close"
            @click="handleViscosityDialogClose"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Leafer, Line, Image, Box, PointerEvent } from 'leafer-ui'
import Point from '@/assets/images/point.png'
import zz from '@/assets/images/zz.webp'
import z81 from '@/assets/images/81z.webp'
import z701 from '@/assets/images/701z.webp'
import bkz from '@/assets/images/bkz.webp'
import wehz from '@/assets/images/wehz.webp'
// import addImg from '@/assets/images/add.png'
// import editImg from '@/assets/images/edit.png'
import addImg from '@/assets/images/addImg2.png'
import editImg from '@/assets/images/editImg2.png'
import { Check, Close, Delete } from '@element-plus/icons-vue'
import { getOilList, editOil, deleteOil } from '@/api/oil'
import {
  getPipeParametersList,
  getOilPumpParametersList,
  getStationRunParametersList,
  modifyStationRunParameters
} from '@/api/parameters'
import { getRealData } from '@/api/scada'
import { ref, onMounted, nextTick, onUnmounted, computed, watch } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'

let leafer
// 获取scada实时数据
const scadaData = ref({})
let z811Box, zz1Box, z7011Box, bkz1Box, wehz1Box
const getRealDataList = async () => {
  const container = document.getElementById('map')
  const { width, height } = container.getBoundingClientRect()
  const res = await getRealData()
  scadaData.value = res.data
  console.log(scadaData.value.JYDBYZPT050221)
  // 创建数据信息盒子
  z811Box = new Box({
    x: width * 0.34 - 150,
    y: height * 0.75 - 150,
    fill: 'rgba(17, 26, 51, 0.80)',
    cornerRadius: 8,
    strokeWidth: 3, // 添加边框宽度
    stroke: 'rgba(255, 255, 255, 0.45)', // 添加边框颜色
    shadow: {
      blur: 10,
      color: 'rgba(0, 0, 0, 0.3)',
      offsetY: 20
    },
    children: [
      {
        tag: 'Text',
        text: `压力: ${scadaData.value.JYDBYZPT050221.toFixed(2)}MPa\n流量: ${scadaData.value.flow_81_701['出站流量'].toFixed(2)}m³/h\n温度: ${scadaData.value.JYDBYZTT050208.toFixed(2)}°C`,
        fill: 'white',
        padding: [10, 20],
        fontSize: 14,
        textAlign: 'left',
        verticalAlign: 'top'
      }
    ]
  })

  zz1Box = new Box({
    x: width * 0.36 - 300,
    y: height * 0.83 - 15,
    fill: 'rgba(17, 26, 51, 0.80)',
    strokeWidth: 3, // 添加边框宽度
    stroke: 'rgba(255, 255, 255, 0.45)', // 添加边框颜色
    cornerRadius: 8,
    shadow: {
      blur: 10,
      color: 'rgba(0, 0, 0, 0.1)',
      offsetY: 4
    },
    children: [
      {
        tag: 'Text',
        text: `压力: ${scadaData.value.KDXZHZPT1101A.toFixed(2)}MPa\n流量: ${scadaData.value.flow_701_z['进站流量'].toFixed(2)} m³/h\n温度: ${scadaData.value.KDXZHZTT1101.toFixed(2)}°C`,
        fill: 'white',
        padding: [10, 20],
        fontSize: 14,
        textAlign: 'left',
        verticalAlign: 'top'
      }
    ]
  })

  z7011Box = new Box({
    x: width * 0.39 + 15,
    y: height * 0.735 + 45,
    fill: 'rgba(17, 26, 51, 0.80)',
    strokeWidth: 3, // 添加边框宽度
    stroke: 'rgba(255, 255, 255, 0.45)', // 添加边框颜色
    cornerRadius: 8,
    shadow: {
      blur: 10,
      color: 'rgba(0, 0, 0, 0.1)',
      offsetY: 4
    },
    children: [
      {
        tag: 'Text',
        text: `百克线进站压力: ${scadaData.value.KWXA701PT1111.toFixed(2)}MPa            出站压力: ${scadaData.value.KWXA701PT1121.toFixed(2)}MPa\n百克线进站流量: ${scadaData.value.flow_bk_701['进站流量'].toFixed(2)} m³/h        出站流量: ${scadaData.value.flow_bk_701['出站流量'].toFixed(2)} m³/h\n百克线进站温度: ${scadaData.value.KWXA701TE1111.toFixed(2)}°C            出站温度: ${scadaData.value.KWXA701TE1121.toFixed(2)}°C\n81#线进站压力: ${scadaData.value.KWXA701PT1091.toFixed(2)}MPa\n81#线进站流量: ${scadaData.value.flow_81_701['出站流量'].toFixed(2)} m³/h\n81#线进站温度: ${scadaData.value.KWXA701TE1091.toFixed(2)}°C   `,
        fill: 'white',
        padding: [10, 20],
        fontSize: 14,
        textAlign: 'left',
        verticalAlign: 'top'
      }
    ]
  })

  bkz1Box = new Box({
    x: width * 0.495 + 15,
    y: height * 0.5 + 45,
    fill: 'rgba(17, 26, 51, 0.80)',
    cornerRadius: 8,
    strokeWidth: 3, // 添加边框宽度
    stroke: 'rgba(255, 255, 255, 0.45)', // 添加边框颜色
    shadow: {
      blur: 10,
      color: 'rgba(0, 0, 0, 0.1)',
      offsetY: 4
    },
    children: [
      {
        tag: 'Text',
        text: `进站压力: ${scadaData.value.JYZDBKZPT1201.toFixed(2)}MPa           出站压力: ${scadaData.value.JYZDBKZPT101.toFixed(2)}MPa\n进站流量: ${scadaData.value.flow_weh_bk['进站流量'].toFixed(2)} m³/h         出站流量: ${scadaData.value.flow_weh_bk['出站流量'].toFixed(2)} m³/h\n进站温度: ${scadaData.value.JYZDBKZTT1201.toFixed(2)}°C            出站温度: ${scadaData.value.JYZDBKZTT302.toFixed(2)}°C`,
        fill: 'white',
        padding: [10, 20],
        fontSize: 14,
        textAlign: 'left',
        verticalAlign: 'top'
      }
    ]
  })

  wehz1Box = new Box({
    x: width * 0.66 + 15,
    y: height * 0.21 + 45,
    fill: 'rgba(17, 26, 51, 0.80)',
    cornerRadius: 8,
    strokeWidth: 3, // 添加边框宽度
    stroke: 'rgba(255, 255, 255, 0.45)', // 添加边框颜色
    shadow: {
      blur: 10,
      color: 'rgba(0, 0, 0, 0.1)',
      offsetY: 4
    },
    children: [
      {
        tag: 'Text',
        text: `压力: ${scadaData.value.WEHXYZPT109.toFixed(2)}MPa\n流量: ${scadaData.value.flow_weh_bk['进站流量'].toFixed(2)} m³/h\n温度: ${scadaData.value.WEHXYZTE102.toFixed(2)}°C`,
        fill: 'white',
        padding: [10, 20],
        fontSize: 14,
        textAlign: 'left',
        verticalAlign: 'top'
      }
    ]
  })

  leafer.add(z811Box)
  leafer.add(zz1Box)
  leafer.add(z7011Box)
  leafer.add(bkz1Box)
  leafer.add(wehz1Box)
}

const pipelineList = ref([
  { id: 1, value: '乌百线' },
  { id: 2, value: '百克站-701线' },
  { id: 3, value: '701-总站' },
  { id: 4, value: '81#-701线' }
])

const isActiveParams = ref(false)
const isActiveTable = ref(false)
const dialogParamsVisible = ref(false)
const pipelineDialogVisible = ref(false)
const chartRef = ref(null)
let chart = null // 保存图表实例

// 修改 activeTab 的认值为 'info'
const activeTab = ref('params1')

// 运行参数限制
const curIndex = ref(1)
const changeCurIndex = (id) => {
  curIndex.value = id
}
const buttons = ref([
  {
    id: 1,
    name: '乌-百线'
  },
  {
    id: 2,
    name: '百-克线 '
  },
  {
    id: 3,
    name: '新81#-701线'
  },
  {
    id: 4,
    name: '701-总站线'
  }
])

const pipelineInfo = ref({
  // 1: {
  //   // 乌-百线
  //   pipeline_name: '乌-百线',
  //   material: 'L415',
  //   diameter: '219',
  //   wall_thickness: '6',
  //   design_pressure: '4',
  //   insulation_thickness: '30',
  //   anti_corrosion_material: '高密度聚乙烯保护层',
  //   notes: '',
  //   pumps: [
  //     { valve_pool_name: '乌-百线1#阀池', mileage: '0.17' },
  //     { valve_pool_name: '乌-百线2#阀池', mileage: '1.65' },
  //     { valve_pool_name: '乌-百线3#阀池', mileage: '13.42' }
  //   ]
  // },
  // 2: {
  //   // 百-克线
  //   pipeline_name: '百-克线',
  //   material: 'L415',
  //   diameter: '377',
  //   wall_thickness: '7',
  //   design_pressure: '3.6',
  //   insulation_thickness: '30',
  //   anti_corrosion_material: '高密度聚乙烯保护层',
  //   notes: '',
  //   pumps: [
  //     { valve_pool_name: '百-克线1#阀池', mileage: '0.25' },
  //     { valve_pool_name: '百-克线2#阀池', mileage: '2.15' }
  //   ]
  // },
  // 3: {
  //   // 新81#-701线
  //   pipeline_name: '新81#-701线',
  //   material: 'L415',
  //   diameter: '219',
  //   wall_thickness: '6',
  //   design_pressure: '4',
  //   insulation_thickness: '30',
  //   anti_corrosion_material: '高密度聚乙烯保护层',
  //   notes: '',
  //   pumps: [{ valve_pool_name: '', mileage: '' }]
  // },
  // 4: {
  //   // 701-总站线
  //   pipeline_name: '701-总站线',
  //   material: 'L415',
  //   diameter: '377',
  //   wall_thickness: '7',
  //   design_pressure: '3.6',
  //   insulation_thickness: '30',
  //   anti_corrosion_material: '高密度聚乙烯保护层',
  //   notes: '',
  //   pumps: [{ valve_pool_name: '', mileage: '' }]
  // }
})

// 计算当前选中的管线数据
const currentPipelineData = computed(() => {
  const data = pipelineInfo.value[curIndex.value]
  return data ? [data] : []
})

// 计算当前选中的泵池数据
const currentPumpData = computed(() => {
  const data = pipelineInfo.value[curIndex.value]
  return data ? data.pumps : []
})

// 监听 curIndex 变化,更新图表
watch(curIndex, () => {
  nextTick(() => {
    updatePipelineChart()
  })
})

// 更新管道纵断面图
const pipelineChartRef = ref(null)
let pipelineChart = null

const updatePipelineChart = () => {
  if (!pipelineChartRef.value) return
  if (!pipelineChart) {
    pipelineChart = echarts.init(pipelineChartRef.value)
  }

  // 根据 curIndex 获取对应的图表数据
  const option = {
    grid: {
      left: '3%',
      right: '7%',
      bottom: '3%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderColor: '#4E7DD0',
      formatter: function (params) {
        return `
        <div style="text-align: left;">
            里程：${params[0].data[0]} km<br/>
            高程：${params[0].data[1]} m
        </div>
    `
      },
      textStyle: {
        color: '#333'
      }
    },
    title: {
      text: currentPipelineData.value[0].pipeline_name,
      textStyle: {
        // color: '#fff',
        fontSize: 16
      },
      top: 0,
      left: 'center'
    },
    xAxis: {
      type: 'value',
      name: '里程(km)'
    },
    yAxis: {
      type: 'value',
      name: '高程(m)'
    },
    series: [
      {
        data: getPipelineChartData(curIndex.value),
        type: 'line',
        smooth: true,
        lineStyle: {
          color: '#4E7DD0',
          width: 3
        },
        symbol: 'circle',
        symbolSize: 0,
        itemStyle: {
          color: '#ffffff',
          borderColor: '#4E7DD0',
          borderWidth: 2,
          shadowColor: 'rgba(255, 255, 255, 0.8)',
          shadowBlur: 10
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(78, 125, 208, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(78, 125, 208, 0)'
              }
            ]
          }
        }
      }
    ]
  }

  pipelineChart.setOption(option)
}

const chartDataMap = ref({
  1: [], // 乌-百线
  2: [], // 百-克线
  3: [], // 新81#-701线
  4: [] // 701-总站线
})
// 获取管道纵断面图数据
const getPipelineChartData = (index) => {
  return chartDataMap.value[index] || []
}

watch(dialogParamsVisible, (val) => {
  if (val) {
    nextTick(() => {
      updatePipelineChart()
    })
  } else {
    if (pipelineChart) {
      pipelineChart.dispose()
      pipelineChart = null
    }
  }
})

// 获取管道及站场基础参数
const getPipelineParameters = async () => {
  const res = await getPipeParametersList()
  // 转换数据格式
  const transformedData = res.data.reduce((acc, item) => {
    acc[item.id] = {
      pipeline_name: item.pipeline_name,
      material: item.material,
      diameter: item.diameter,
      wall_thickness: item.wall_thickness,
      design_pressure: item.design_pressure,
      insulation_thickness: item.insulation_thickness,
      anti_corrosion_material: item.anti_corrosion_material,
      notes: item.notes,
      pumps:
        item.pumps.length > 0
          ? item.pumps.map((pump) => ({
              valve_pool_name: pump.valve_pool_name,
              mileage: pump.mileage
            }))
          : [{ valve_pool_name: '', mileage: '' }] // 如果 pumps 为空，返回默认值
    }
    return acc
  }, {})

  const transformedData2 = res.data.reduce((acc, item) => {
    acc[item.id] = item.pipeline_sections.map((section) => [section.mileage, section.elevation])
    return acc
  }, {})
  console.log('🐯 ~ transformedData2 ~ transformedData2:', transformedData2)
  chartDataMap.value = transformedData2
  // 将转换后的数据赋值给 pipelineInfo
  pipelineInfo.value = transformedData
  console.log(pipelineInfo.value)
}
getPipelineParameters()

// 输油泵参数表
const pumpParamsData = ref([])

// 添加合并单元格的方法
const pumpParamsSpanMethod = ({ row, column, rowIndex }) => {
  if (column.property === 'station_name') {
    const stations = pumpParamsData.value.map((item) => item.station_name)
    let count = 1
    let prevIndex = 0

    // 计算当前行之前有多少相同站名
    for (let i = 0; i < rowIndex; i++) {
      if (stations[i] === stations[i + 1]) {
        count++
        prevIndex = i + 1 - (count - 1)
      } else {
        count = 1
        prevIndex = i + 1
      }
    }

    // 如果是相同站名的第一行，则合并
    if (rowIndex === prevIndex) {
      const sameName = stations.filter(
        (name, index) => index >= rowIndex && name === stations[rowIndex]
      ).length
      return {
        rowspan: sameName,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

const getOilPumpList = async () => {
  const res = await getOilPumpParametersList()
  pumpParamsData.value = res.data
}
getOilPumpList()

// 站场运行参数保护设定值
const stationParamsData = ref([])

const stationParamsSpanMethod = ({ row, column, rowIndex }) => {
  // 只处理站场名称列的合并
  if (column.property === 'station_name') {
    const stations = stationParamsData.value

    // 如果是第一行或前一行的站名与当前行不同，开始一个新的合并
    if (rowIndex === 0 || stations[rowIndex - 1].station_name !== stations[rowIndex].station_name) {
      // 计算当前站名连续出现的次数
      let count = 1
      for (let i = rowIndex + 1; i < stations.length; i++) {
        if (stations[i].station_name === stations[rowIndex].station_name) {
          count++
        } else {
          break
        }
      }

      return {
        rowspan: count,
        colspan: 1
      }
    } else {
      // 非首行且与前一行站名相同，则被合并
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }

  // 其他列不合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

const getStationRunList = async () => {
  const res = await getStationRunParametersList()
  stationParamsData.value = res.data
}
getStationRunList()

// 添加处理单元格修改的方法
const handleCellChange = async (row) => {
  try {
    const params = {
      id: row.id,
      station_name: row.station_name,
      location: row.location,
      temp_low_low: row.temp_low_low,
      temp_low: row.temp_low,
      temp_high: row.temp_high,
      temp_high_high: row.temp_high_high,
      pressure_low_low: row.pressure_low_low,
      pressure_low: row.pressure_low,
      pressure_high: row.pressure_high,
      pressure_high_high: row.pressure_high_high,
      notes: row.notes
    }

    await modifyStationRunParameters(params)
    getStationRunList()
    ElMessage.success('修改成功')
  } catch (error) {
    ElMessage.error('修改失败')
    // 如果修改失败,重新获取数据以恢复原值
    getStationRunList()
  }
}

// 油品信息数据
const oilData = ref([])

// 新增表单相关的响应式变量
const oilFormVisible = ref(false)
const isEdit = ref(false)

const oilForm = ref({
  oils_name: '',
  chinese_name: '',
  density: '',
  base_viscosity: '',
  // thermal_conductivity: '',
  freezing_point: ''
})

const rules = {
  oils_name: [{ required: true, message: '请输入油品编号', trigger: 'blur' }],
  chinese_name: [{ required: true, message: '请输入油品名称', trigger: 'blur' }],
  density: [{ required: true, message: '请输入密度', trigger: 'blur' }],
  base_viscosity: [{ required: true, message: '请输入基准粘度', trigger: 'blur' }],
  // thermal_conductivity: [{ required: true, message: '请输入导热系数', trigger: 'blur' }],
  freezing_point: [{ required: true, message: '请输入凝点', trigger: 'blur' }]
}

// 添加表单ref
const oilFormRef = ref(null)

// 加运参数表单相关的响应式变量
const paramsFormVisible = ref(false)
const paramsForm = ref({
  id: '',
  station_name: '',
  flow_upper_limit: '',
  flow_lower_limit: '',
  pressure_upper_limit: '',
  pressure_lower_limit: '',
  outlet_pressure_upper_limit: '',
  outlet_pressure_lower_limit: ''
})

const paramsFormRef = ref(null)
const paramsRules = {
  flow_upper_limit: [{ required: true, message: '请输入流量上限', trigger: 'blur' }],
  flow_lower_limit: [{ required: true, message: '请输入流量下限', trigger: 'blur' }],
  pressure_upper_limit: [{ required: true, message: '请输入压力上限', trigger: 'blur' }],
  pressure_lower_limit: [{ required: true, message: '请输入压力下限', trigger: 'blur' }],
  outlet_pressure_upper_limit: [{ required: true, message: '请输入出站压力上限', trigger: 'blur' }],
  outlet_pressure_lower_limit: [{ required: true, message: '请输入出站压力下限', trigger: 'blur' }]
}

// 添加响应式变量
const tableDialogVisible = ref(false)
const parametersData = ref([
  {
    station_name: '乌尔禾稀油站',
    inlet_pressure: '6.61',
    outlet_pressure: '10.70',
    inlet_temperature: '11.7',
    outlet_temperature: '40.4',
    outFlow: '967.4',
    inFlow: '967.4'
  },
  {
    station_name: '百克站',
    inlet_pressure: '6.16',
    outlet_pressure: '6.16',
    inlet_temperature: '24.4',
    outlet_temperature: '24.4',
    outFlow: '967.4',
    inFlow: '967.4'
  },
  {
    station_name: '701站',
    inlet_pressure: '6.16',
    outlet_pressure: '5.08',
    inlet_temperature: '24.4',
    outlet_temperature: '40.0',
    outFlow: '967.4',
    inFlow: '967.4'
  },
  {
    station_name: '81#站',
    inlet_pressure: '7.59',
    outlet_pressure: '9.53',
    inlet_temperature: '26.4',
    outlet_temperature: '26.8',
    outFlow: '967.3',
    inFlow: '967.4'
  },
  {
    station_name: '总站',
    inlet_pressure: '7.69',
    outlet_pressure: '3.20',
    inlet_temperature: '13.6',
    outlet_temperature: '15.4',
    outFlow: '968.0',
    inFlow: '967.4'
  }
])

// 添加新的响应式变量
const pipelineParamsVisible = ref(false)

const router = useRouter()

// 添加点击处理函数
const handlePointClick = (index) => {
  console.log(index)
  router.push({ path: '/originOil/industrialProcesses/graph', query: { id: index } })
}

// 添加选中的管道ID
const selectedPipelineId = ref(1)

// 修改管道选择处理函数
const handlePipelineSelect = (item) => {
  selectedPipelineId.value = item.id
  pipelineDialogVisible.value = true
}

const toggleParams = () => {
  isActiveParams.value = !isActiveParams.value
  dialogParamsVisible.value = !dialogParamsVisible.value
}

const toggleTable = () => {
  isActiveTable.value = !isActiveTable.value
  tableDialogVisible.value = !tableDialogVisible.value
}

const handleParamsDialogClose = () => {
  isActiveParams.value = false
  activeTab.value = 'params1' // 重置为默认 tab
}

// 处理编辑
const handleEdit = (row) => {
  curOil.value = row
  viscosityData.value = row.viscosities
  isEdit.value = true
  oilForm.value = { ...row }
  oilFormVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该油品信息吗？', '提示', {
      type: 'warning'
    })
    await deleteOil({ id: row.id })
    ElMessage.success('删除成功')
    getOilsList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理新增油品
const handleAddOil = () => {
  isEdit.value = false
  oilForm.value = {
    oils_name: '',
    chinese_name: '',
    density: '',
    base_viscosity: '',
    freezing_point: ''
  }
  viscosityData.value = []
  oilFormVisible.value = true
}

// 新增处理函数
const handleOilFormClose = () => {
  oilFormVisible.value = false
  oilForm.value = {
    oils_name: '',
    chinese_name: '',
    density: '',
    base_viscosity: '',
    freezing_point: ''
  }
  // 重置表单验证和值
  oilFormRef.value?.resetFields()
}

// 获取油品列表
const getOilsList = async () => {
  try {
    const res = await getOilList()
    oilData.value = res.data
  } catch (error) {
    ElMessage.error('获取油品列表失败')
  }
}

// 表单提交
const handleOilFormSubmit = async () => {
  await oilFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await editOil({
          ...oilForm.value,
          id: isEdit.value ? oilForm.value.id : undefined,
          viscosities: viscosityData.value
        })
        ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
        handleOilFormClose()
        getOilsList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
      }
    }
  })
}



// 处理参数表单关闭
const handleParamsFormClose = () => {
  paramsFormVisible.value = false
  paramsForm.value = {
    id: '',
    station_name: '',
    flow_upper_limit: '',
    flow_lower_limit: '',
    pressure_upper_limit: '',
    pressure_lower_limit: '',
    outlet_pressure_upper_limit: '',
    outlet_pressure_lower_limit: ''
  }
  // 重置表单验证和值
  paramsFormRef.value?.resetFields()
}

// 添加关闭弹窗处理方法
const handleTableDialogClose = () => {
  isActiveTable.value = false
  tableDialogVisible.value = false
}

// 定义管道数据映射
const pipelineDataMap = ref({
  wubai: {
    name: '乌百线',
    length: '27.0',
    diameter: '219',
    thickness: '6',
    design_capacity: '80',
    design_pressure: '4',
    stations: [
      {
        stationName: '乌尔禾稀油站',
        mileage: '0',
        elevation: '301',
        pumps: [
          {
            pumpNo: '1#',
            pump_power: '176.3',
            pump_head: '460',
            pump_flow: '55'
          },
          {
            pumpNo: '2#',
            pump_power: '176.3',
            pump_head: '460',
            pump_flow: '55'
          },
          {
            pumpNo: '3#',
            pump_power: '176.3',
            pump_head: '460',
            pump_flow: '55'
          }
        ]
      },
      {
        stationName: '百克站',
        mileage: '26.63',
        elevation: '320',
        pumps: [
          {
            pumpNo: '1#',
            pump_power: '400',
            pump_head: '400',
            pump_flow: '260'
          },
          {
            pumpNo: '2#',
            pump_power: '400',
            pump_head: '400',
            pump_flow: '260'
          },
          {
            pumpNo: '3#',
            pump_power: '315',
            pump_head: '400',
            pump_flow: '200'
          },
          {
            pumpNo: '4#',
            pump_power: '75',
            pump_head: '70',
            pump_flow: '200'
          }
        ]
      }
    ]
  },
  baike701: {
    name: '百克-701线',
    length: '45.8',
    diameter: '377',
    thickness: '7',
    design_capacity: '325',
    design_pressure: '3.6',
    stations: [
      {
        stationName: '百克站',
        mileage: '0',
        elevation: '325.2',
        pumps: [
          {
            pumpNo: '1#',
            pump_power: '400',
            pump_head: '400',
            pump_flow: '260'
          },
          {
            pumpNo: '2#',
            pump_power: '400',
            pump_head: '400',
            pump_flow: '260'
          },
          {
            pumpNo: '3#',
            pump_power: '315',
            pump_head: '400',
            pump_flow: '200'
          },
          {
            pumpNo: '4#',
            pump_power: '75',
            pump_head: '70',
            pump_flow: '200'
          }
        ]
      },
      {
        stationName: '701站',
        mileage: '45',
        elevation: '282.7',
        pumps: [
          {
            pumpNo: '混油泵1#',
            pump_power: '75',
            pump_head: '65',
            pump_flow: '350'
          },
          {
            pumpNo: '混油泵2#',
            pump_power: '75',
            pump_head: '65',
            pump_flow: '350'
          },
          {
            pumpNo: '1#调油泵',
            pump_power: '184.7',
            pump_head: '140',
            pump_flow: '400'
          },
          {
            pumpNo: '2#调油泵',
            pump_power: '250',
            pump_head: '140',
            pump_flow: '400'
          },
          {
            pumpNo: '稠油泵',
            pump_power: '41',
            pump_head: '200',
            pump_flow: '46'
          },
          {
            pumpNo: '4#外输泵',
            pump_power: '445',
            pump_head: '4.5MPa',
            pump_flow: '300'
          },
          {
            pumpNo: '5#外输泵',
            pump_power: '250',
            pump_head: '4.5MPa',
            pump_flow: '130'
          },
          {
            pumpNo: '1#喂油泵',
            pump_power: '132',
            pump_head: '50',
            pump_flow: '600'
          },
          {
            pumpNo: '2#喂油泵',
            pump_power: '132',
            pump_head: '50',
            pump_flow: '600'
          },
          {
            pumpNo: '1#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '2#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '3#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '卸油台1#',
            pump_power: '30',
            pump_head: '0.6',
            pump_flow: '100'
          },
          {
            pumpNo: '卸油台2#',
            pump_power: '30',
            pump_head: '0.6',
            pump_flow: '100'
          }
        ]
      }
    ]
  },
  '701zz': {
    name: '701-总站线',
    length: '10.5 ',
    diameter: '377',
    thickness: '7',
    design_capacity: '300	',
    design_pressure: '4.4	',
    stations: [
      {
        stationName: '701#',
        mileage: '0',
        elevation: '274',
        pumps: [
          {
            pumpNo: '混油泵1#',
            pump_power: '75',
            pump_head: '65',
            pump_flow: '350'
          },
          {
            pumpNo: '混油泵2#',
            pump_power: '75',
            pump_head: '65',
            pump_flow: '350'
          },
          {
            pumpNo: '1#调油泵',
            pump_power: '184.7',
            pump_head: '140',
            pump_flow: '400'
          },
          {
            pumpNo: '2#调油泵',
            pump_power: '250',
            pump_head: '140',
            pump_flow: '400'
          },
          {
            pumpNo: '稠油泵',
            pump_power: '41',
            pump_head: '200',
            pump_flow: '46'
          },
          {
            pumpNo: '4#外输泵',
            pump_power: '445',
            pump_head: '4.5MPa',
            pump_flow: '300'
          },
          {
            pumpNo: '5#外输泵',
            pump_power: '250',
            pump_head: '4.5MPa',
            pump_flow: '130'
          },
          {
            pumpNo: '1#喂油泵',
            pump_power: '132',
            pump_head: '50',
            pump_flow: '600'
          },
          {
            pumpNo: '2#喂油泵',
            pump_power: '132',
            pump_head: '50',
            pump_flow: '600'
          },
          {
            pumpNo: '1#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '2#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '3#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '卸油台1#',
            pump_power: '30',
            pump_head: '0.6',
            pump_flow: '100'
          },
          {
            pumpNo: '卸油台2#',
            pump_power: '30',
            pump_head: '0.6',
            pump_flow: '100'
          }
        ]
      },
      {
        stationName: '总站',
        mileage: '10.5',
        elevation: '280',
        pumps: [
          {
            pumpNo: '1#喂油泵',
            pump_power: '15.8',
            pump_head: '11',
            pump_flow: '432'
          },
          {
            pumpNo: '2#喂油泵',
            pump_power: '15.9',
            pump_head: '11',
            pump_flow: '432'
          },
          {
            pumpNo: '1#',
            pump_power: '290',
            pump_head: '130',
            pump_flow: '435'
          },
          {
            pumpNo: '2#',
            pump_power: '500',
            pump_head: '260',
            pump_flow: '435'
          },
          {
            pumpNo: '3#',
            pump_power: '500',
            pump_head: '260',
            pump_flow: '435'
          },
          {
            pumpNo: '4#',
            pump_power: '500',
            pump_head: '260',
            pump_flow: '435'
          },
          {
            pumpNo: '5#',
            pump_power: '500',
            pump_head: '260',
            pump_flow: '435'
          },
          {
            pumpNo: '6#',
            pump_power: '450',
            pump_head: '760',
            pump_flow: '140'
          },
          {
            pumpNo: '7#',
            pump_power: '450',
            pump_head: '760',
            pump_flow: '140'
          }
        ]
      }
    ]
  },
  81701: {
    name: '81#-701线',
    length: '15.0',
    diameter: '325',
    thickness: '7',
    design_capacity: '200',
    design_pressure: '4',
    stations: [
      {
        stationName: '81#站',
        mileage: '0',
        elevation: '268.6',
        pumps: [
          {
            pumpNo: '1#',
            pump_power: '400',
            pump_head: '400',
            pump_flow: '260'
          },
          {
            pumpNo: '2#',
            pump_power: '400',
            pump_head: '400',
            pump_flow: '260'
          },
          {
            pumpNo: '3#',
            pump_power: '315',
            pump_head: '400',
            pump_flow: '200'
          },
          {
            pumpNo: '4#',
            pump_power: '75',
            pump_head: '70',
            pump_flow: '200'
          }
        ]
      },
      {
        stationName: '701#站',
        mileage: '15',
        elevation: '280.2',
        pumps: [
          {
            pumpNo: '混油泵1#',
            pump_power: '75',
            pump_head: '65',
            pump_flow: '350'
          },
          {
            pumpNo: '混油泵2#',
            pump_power: '75',
            pump_head: '65',
            pump_flow: '350'
          },
          {
            pumpNo: '1#调油泵',
            pump_power: '184.7',
            pump_head: '140',
            pump_flow: '400'
          },
          {
            pumpNo: '2#调油泵',
            pump_power: '250',
            pump_head: '140',
            pump_flow: '400'
          },
          {
            pumpNo: '稠油泵',
            pump_power: '41',
            pump_head: '200',
            pump_flow: '46'
          },
          {
            pumpNo: '4#外输泵',
            pump_power: '445',
            pump_head: '4.5MPa',
            pump_flow: '300'
          },
          {
            pumpNo: '5#外输泵',
            pump_power: '250',
            pump_head: '4.5MPa',
            pump_flow: '130'
          },
          {
            pumpNo: '1#喂油泵',
            pump_power: '132',
            pump_head: '50',
            pump_flow: '600'
          },
          {
            pumpNo: '2#喂油泵',
            pump_power: '132',
            pump_head: '50',
            pump_flow: '600'
          },
          {
            pumpNo: '1#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '2#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '3#外输泵',
            pump_power: '560',
            pump_head: '240',
            pump_flow: '600'
          },
          {
            pumpNo: '卸油台1#',
            pump_power: '30',
            pump_head: '0.6',
            pump_flow: '100'
          },
          {
            pumpNo: '卸油台2#',
            pump_power: '30',
            pump_head: '0.6',
            pump_flow: '100'
          }
        ]
      }
    ]
  }
})
// 添加 pipelineData 的定义
const pipelineData = ref(pipelineDataMap.value.wubai) // 设置默认值为乌百线数据
// 修改双击事件处理函数
function onDoubleClick(e) {
  // console.log("🚀 ~ onDoubleClick ~ e:", e.target)
  const pipelineKey = e.target.pipelineKey
  if (pipelineKey && pipelineDataMap.value[pipelineKey]) {
    pipelineData.value = pipelineDataMap.value[pipelineKey]
    console.log('🚀 ~ onDoubleClick ~ pipelineData.value:', pipelineData.value.name)
    pipelineParamsVisible.value = true
  }
}

// 添加一个计算每个站点的泵数量的函数
const getStationPumpsCounts = (pipeline) => {
  return pipeline.stations.map((station) => station.pumps.length)
}

// 修改 objectSpanMethod 方法
const objectSpanMethod = ({ row, column, rowIndex }) => {
  const pumpsCounts = getStationPumpsCounts(pipelineData.value)

  // 计算当前行属于哪个站场
  let currentStation = 0
  let rowCount = 0
  let startIndex = 0

  // 遍历找出当前行属于哪个站场
  for (let i = 0; i < pumpsCounts.length; i++) {
    if (rowIndex >= startIndex && rowIndex < startIndex + pumpsCounts[i]) {
      currentStation = i
      rowCount = pumpsCounts[i]
      break
    }
    startIndex += pumpsCounts[i]
  }

  // 判断是否是站场的第一行
  const isFirstRowOfStation = rowIndex === startIndex

  // 需要合并的列：站场名称、里程、高程
  if (['stationName', 'mileage', 'elevation'].includes(column.property)) {
    if (isFirstRowOfStation) {
      return {
        rowspan: rowCount, // 使用实际的泵数量
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

// 修改数据处理方法，将站场和泵的数据展平
const getTableData = (pipeline) => {
  const flatData = []
  pipeline.stations.forEach((station) => {
    station.pumps.forEach((pump) => {
      flatData.push({
        stationName: station.stationName,
        mileage: station.mileage,
        elevation: station.elevation,
        ...pump
      })
    })
  })
  return flatData
}

// 在 script setup 中添加以下代码
const viscosityDialogVisible = ref(false)
const viscosityData = ref([{ viscosity: '', temperature: '' }])

// 处理粘度关系点击
const curOil = ref(null)
const isEdit2 = ref(false)
const handleViscosityEdit = (row) => {
  console.log('🐯 ~ handleViscosityEdit ~ row:', row)
  isEdit2.value = true
  curOil.value = row
  viscosityData.value = row.viscosities
  viscosityDialogVisible.value = true
}
const handleViscosityEdit2 = () => {
  if (isEdit.value) {
    viscosityData.value = curOil.value.viscosities
    viscosityDialogVisible.value = true
  } else {
    viscosityDialogVisible.value = true
  }
}

// 添加新行
const addViscosityRow = () => {
  viscosityData.value.push({
    viscosity: '',
    temperature: ''
  })
}

// 处理确认
const handleViscosityConfirm = async () => {
  // 这里可以添加数据验证和保存逻辑
  if (isEdit.value || isEdit2.value) {
    try {
      await editOil({
        ...curOil.value,
        viscosities: viscosityData.value
      })
      ElMessage.success('修改成功')
      handleViscosityDialogClose()
      getOilsList()
    } catch (error) {
      ElMessage.error('修改失败')
    }
  }

  viscosityDialogVisible.value = false
}

// 处理关闭
const handleViscosityDialogClose = () => {
  isEdit2.value = false

  viscosityDialogVisible.value = false
}

// 添加删除行方法
const deleteViscosityRow = (index) => {
  viscosityData.value.splice(index, 1)
}

onMounted(() => {
  const container = document.getElementById('map')
  const { width, height } = container.getBoundingClientRect()
  console.log('🚀 ~ onMounted ~ width, height:', width, height)
  leafer = new Leafer({
    view: 'map',
    width,
    height
  })
  getRealDataList()
  getOilsList()

  // 创建4条管道线
  // 1. 乌百线
  const wubaiLine = new Line({
    points: [
      width * 0.495,
      height * 0.5, // 3
      width * 0.58,
      height * 0.38,
      width * 0.6,
      height * 0.36,
      width * 0.63,
      height * 0.3,
      width * 0.65,
      height * 0.22,
      width * 0.66,
      height * 0.21 // 4
    ],
    strokeWidth: 10,
    stroke: '#4E7DD0',
    curve: true,
    pipelineKey: 'wubai'
  })
  wubaiLine.on(PointerEvent.DOUBLE_CLICK, onDoubleClick)

  // 2. 百克-701#线
  const baike701Line = new Line({
    points: [
      width * 0.39,
      height * 0.735,
      width * 0.41,
      height * 0.71,
      width * 0.495,
      height * 0.5
    ],
    strokeWidth: 10,
    stroke: '#4E7DD0',
    curve: true,
    pipelineKey: 'baike701'
  })
  baike701Line.on(PointerEvent.DOUBLE_CLICK, onDoubleClick)

  // 3. 701#-总站线
  const zz701Line = new Line({
    points: [width * 0.39, height * 0.735, width * 0.36, height * 0.83],
    strokeWidth: 10,
    stroke: '#4E7DD0',
    curve: true,
    pipelineKey: '701zz'
  })
  zz701Line.on(PointerEvent.DOUBLE_CLICK, onDoubleClick)

  // 4. 81#-701#线
  const line81701 = new Line({
    points: [width * 0.34, height * 0.75, width * 0.39, height * 0.735],
    strokeWidth: 10,
    stroke: '#4E7DD0',
    curve: true,
    pipelineKey: '81701'
  })
  line81701.on(PointerEvent.DOUBLE_CLICK, onDoubleClick)

  // 添加所有线段到leafer
  leafer.add(wubaiLine)
  leafer.add(baike701Line)
  leafer.add(zz701Line)
  leafer.add(line81701)

  // 修改 point0 的创建
  const point0 = new Image({
    url: Point,
    x: width * 0.34 - 12,
    y: height * 0.75 - 12,
    width: 24,
    height: 24,
    cursor: 'pointer'
  })
  point0.on(PointerEvent.CLICK, () => handlePointClick(4))

  // 修改 point1 的创建
  const point1 = new Image({
    url: Point,
    x: width * 0.36 - 12,
    y: height * 0.83 - 12,
    width: 24,
    height: 24,
    cursor: 'pointer'
  })
  point1.on(PointerEvent.CLICK, () => handlePointClick(5))

  // 修改 point2 的创建
  const point2 = new Image({
    url: Point,
    x: width * 0.39 - 12,
    y: height * 0.735 - 12,
    width: 24,
    height: 24,
    cursor: 'pointer'
  })
  point2.on(PointerEvent.CLICK, () => handlePointClick(3))

  // 修改 point3 的创建
  const point3 = new Image({
    url: Point,
    x: width * 0.495 - 12,
    y: height * 0.5 - 12,
    width: 24,
    height: 24,
    cursor: 'pointer'
  })
  point3.on(PointerEvent.CLICK, () => handlePointClick(2))

  // 修改 point4 的创建
  const point4 = new Image({
    url: Point,
    x: width * 0.66 - 12,
    y: height * 0.21 - 12,
    width: 24,
    height: 24,
    cursor: 'pointer'
  })
  point4.on(PointerEvent.CLICK, () => handlePointClick(1))

  // 在点0旁边添加zz图片
  const z811 = new Image({
    url: z81,
    x: width * 0.34 - 150, // 在点1右侧显示
    y: height * 0.75 - 50, // 与点1垂直对齐
    width: 136,
    height: 46
  })
  // 在点1旁添加zz图片
  const zz1 = new Image({
    url: zz,
    x: width * 0.36 - 150, // 在点1右侧显示
    y: height * 0.83 - 15, // 点1垂直对齐
    width: 136,
    height: 46
  })

  // 在点2旁边添加zz图片
  const z7011 = new Image({
    url: z701,
    x: width * 0.39 + 15, // 在点1右侧显示
    y: height * 0.735 - 15, // 与点1垂直对齐
    width: 136,
    height: 46
  })

  // 在点3旁边添加zz图片
  const bkz1 = new Image({
    url: bkz,
    x: width * 0.495 + 15, // 在点1右侧显示
    y: height * 0.5 - 15, // 与点1垂直对齐
    width: 136,
    height: 46
  })

  // 在点4旁边添加zz图片
  const wehz1 = new Image({
    url: wehz,
    x: width * 0.66 + 15, // 在点1右侧显示
    y: height * 0.21 - 15, // 与点1垂直对齐
    width: 136,
    height: 46
  })

  leafer.add(z811)
  leafer.add(zz1)
  leafer.add(z7011)
  leafer.add(bkz1)
  leafer.add(wehz1)

  leafer.add(point0)
  leafer.add(point1)
  leafer.add(point2)
  leafer.add(point3)
  leafer.add(point4)
})

onUnmounted(() => {
  leafer.destroy()
})
</script>

<style lang="scss" scoped>
.imgBg {
  background-image: url('@/assets/images/oil_bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  overflow: hidden;
}

:deep(.el-dialog__header .el-dialog__title) {
  font-size: 16px;
  margin-left: 20px;
}

:deep(.parameters-table-dialog) {
  .el-dialog__header {
    text-align: center;
    margin-right: 0;
    .el-dialog__title {
      font-size: 18px;
      font-weight: bold;
    }
  }
}

:deep(.pipeline-dialog) {
  .el-dialog__body {
    // background: #404040;
  }
}

.pipeline-params-table {
  :deep(.el-table) {
    // 设置表格背景色为白色
    // --el-table-bg-color: #ffffff;

    // 设置表头样式
    .el-table__header {
      th {
        // background-color: #f5f7fa;
        // color: #000000;
        font-weight: 500;
      }
    }

    // 设置单元格样式
    .el-table__cell {
      padding: 8px 0;
    }
  }
}

// 设置dialog样式
:deep(.el-dialog) {
  .el-dialog__header {
    text-align: center;
    margin-right: 0;
    padding-bottom: 0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .el-dialog__body {
    padding-top: 20px;
  }
}

.custom-button {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  padding: 0 20px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #4678b2;
  color: #4678b2;
  background-color: #e8edf4;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    color: white;
    border-color: #5889bf;
    background-color: #4678b2;
  }
}

:deep(.params-dialog.el-dialog) {
  height: 520px;
  // background: linear-gradient(to right, rgba(23, 64, 105, 1), rgba(18, 29, 55, 1));
}
:deep(.el-tabs__content) {
  // background: linear-gradient(to right, rgba(23, 64, 105, 1), rgba(18, 29, 55, 1));
}

:deep(.el-tabs--border-card) {
  border: none;
}
:deep(.el-tabs__header) {
  // background-color: rgba(26, 40, 77, 1);
  // border: none;
}
:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
  // border: none;
  // border-radius: 6px;
  &:hover {
    // color: white;
  }
}
:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  // color: white;
  // background-color: rgba(56, 99, 147, 1);
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  // color: white !important;
}

.custom-button2 {
  // background-color: rgba(155, 222, 246, 0.18);
  // color: #9bdef6;
  // border: 1px solid #9bdef6;
  // &:hover {
  //   background-color: rgba(155, 222, 246, 0.38);
  // }
  background-color: rgba(69, 122, 178, 0.18);
  color: rgba(69, 122, 178, 0.8);
  border: 1px solid rgba(69, 122, 178, 0.8);
  &:hover {
    background-color: rgba(69, 122, 178, 0.38);
  }
  font-size: 12px;
  font-weight: 400;
  padding: 0 16px;
  border-radius: 4px;
  line-height: 30px;
  cursor: pointer;
}

.custom-button3 {
  background-color: rgba(69, 122, 178, 0.1);
  color: rgba(69, 122, 178, 1) !important;
  border: 1px solid rgba(69, 122, 178, 1);
  font-weight: 400;
  width: 70px !important;
  font-size: 12px;
  border-radius: 4px;
  line-height: 30px;
  cursor: pointer;
  &:hover {
    background-color: rgba(69, 122, 178, 0.38);
  }
}
.custom-button4 {
  background-color: rgba(245, 108, 108, 0.18);
  color: rgba(245, 108, 108, 1) !important;
  border: 1px solid rgba(245, 108, 108, 1);
  font-weight: 400;
  width: 70px !important;
  font-size: 12px;
  border-radius: 4px;
  line-height: 30px;
  cursor: pointer;
  &:hover {
    background-color: rgba(245, 108, 108, 0.38);
  }
}

.custom-button5 {
  // background-image: url('../../assets/images/unActive_bg.png');
  background-color: rgba(69, 122, 178, 0.18);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border: 1px solid rgba(69, 122, 178, 1);
  border-radius: 6px;
  color: rgba(69, 122, 178, 0.8);
  width: 140px;
  height: 40px;

  cursor: pointer;
}

.custom-button6 {
  // background-image: url('../../assets/images/active_bg.png');
  background-color: rgba(69, 122, 178, 1);
  border: 1px solid rgba(69, 122, 178, 1);
  color: white;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 6px;
}

.viscosity-table {
  :deep(.el-input__wrapper) {
    box-shadow: none;
    padding: 0;
  }
  :deep(.el-input__wrapper.is-focus) {
    box-shadow: none !important;
    border: none;
  }
}

// 添加输入框样式
:deep(.el-input) {
  .el-input__inner {
    padding: 0 8px;
    text-align: center;
  }
}
</style>
